<template>
    <!--消息列表组件 数据交互频繁-->
    <!--进入 dialogue 页面，携带参数 mid name group_num -->
    <li :class="{'item-hide':deleteMsg}">
        <!--自定义指令 v-swiper 用于对每个消息进行滑动处理-->
        <router-link
            :to="{ path: '/wechat/dialogue', query: { mid: item.mid,name:item.group_name||(item.user[0].remark||item.user[0].nickname),group_num:item.user.length}}"
            tag="div" class="list-info" v-swiper v-on:click.native="toggleMsgRead($event,'enter')">
            <div class="header-box">
              <i class="new-msg-count" v-show="item.newMsgCount > 0">{{item.newMsgCount}}</i>
                <i class="new-msg-dot" v-show="!read&&item.quiet"></i>
                <div class="header" :class="[item.type=='group'?'multi-header':'']">
                  <img :src="getImageSrc(item.group_name)">
                </div>
            </div>
            <div class="desc-box">
                <!--使用过滤器 fmtDate 格式化时间-->
                <div class="desc-time">{{fmtDate(item.latestMessageTime) }}</div>
                <div class="desc-author" v-if="item.type=='group'">{{item.group_name}}</div>
                <!--如果没有备注好友，则显示微信昵称-->
                <div class="desc-author" v-else>{{item.user[0].remark||item.user[0].nickname}}</div>
                <div class="desc-msg">
<!--                    <div class="desc-mute iconfont icon-mute" v-show="item.quiet">-->
<!--                    </div>-->
<!--                    <span>{{item.msg[item.msg.length-1].text}}</span>-->
                  <span v-html="parseMessageText(item.msg[item.msg.length-1].text)"></span>
                </div>
            </div>
        </router-link>
    </li>
</template>
<script>
    export default {
        props: ["item"],
        data() {
            return {
                read: this.item.read,
                deleteMsg: false,
              randomBackgroundColor: this.getRandomColor()
            }
        },
        methods: {
          parseMessageText(text) {
            // 正则表达式用于匹配 ![](image_url) 格式的文本
            const imgRegex = /!\[\]\((https:\/\/[^)]+)\)/g;
            text = text.replace(imgRegex, "[图片]")
            const stockRegex = /\$\$(.+?)-(\d+)/g;
            text =  text.replace(stockRegex, (match, stockName, stockCode) => {
              const linkPrefix = stockCode.startsWith('0') || stockCode.startsWith('3') ? 'SZ' : 'SH';
              const stockLink = `https://xueqiu.com/S/${linkPrefix}${stockCode}`;
              return `<a href="${stockLink}" target="_blank" style = "color: blue; font-weight: bold;">${stockName}(${stockCode})</a>`;
            });
            return text;
          },
          // 添加一个新方法来获取图片的完整路径
          getImageSrc(groupName) {
            return `images/header/${groupName}.png`;
          },

          // 添加一个生成随机颜色的方法
          getRandomColor() {
            // 使用较低的颜色值来生成暗色调
            let color = '#';
            for (let i = 0; i < 3; i++) {
              // 生成 0 到 127 之间的值，保证颜色较暗
              color += Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            }
            return color;
          },
            // 格式化时间
          fmtDate(latestMessageTime) {
            const messageDate = new Date(latestMessageTime);
            const now = new Date();

            // 检查年、月、日是否相同
            if (messageDate.getFullYear() === now.getFullYear() &&
                messageDate.getMonth() === now.getMonth() &&
                messageDate.getDate() === now.getDate()) {
              // 如果是当天，返回小时和分钟，左补0
              let hours = messageDate.getHours().toString().padStart(2, '0');
              let minutes = messageDate.getMinutes().toString().padStart(2, '0');
              return `${hours}:${minutes}`;
            } else {
              // 如果不是当天，返回月份和日期，月份和日期左补0
              let month = (messageDate.getMonth() + 1).toString().padStart(2, '0');
              let day = messageDate.getDate().toString().padStart(2, '0');
              return `${month}月${day}日`;
            }
          }
            ,


    //切换消息未读/已读状态
            toggleMsgRead(event, status) {
                if (status === 'enter') {
                    this.$store.commit('clearNewMsgCount', this.item)
                    this.read = true
                } else {
                    this.read = !this.read
                }
                if (!this.item.quiet) {
                    if (this.read) {
                        this.$store.commit('minusNewMsg')
                    } else {
                        this.$store.commit('addNewMsg')
                    }
                }

                event.target.parentNode.parentNode.firstChild.style.marginLeft = 0 + "px"
            },
            deleteMsgEvent() {
                this.deleteMsg = true
                if (!this.item.quiet) {
                    if (!this.read) {
                        this.$store.commit('minusNewMsg')
                    }
                }
            }
        },
        // 参考 https://vuefe.cn/v2/guide/custom-directive.html
        directives: {
            swiper: {
                bind: function (element) {
                    var isTouchMove, startTx, startTy
                    element.addEventListener('touchstart', function (e) {
                        var touches = e.touches[0]
                        startTx = touches.clientX
                        startTy = touches.clientY
                        isTouchMove = false;
                    });
                    element.addEventListener('touchmove', function (e) {
                       // e.preventDefault();
                        var touches = e.changedTouches[0],
                            endTx = touches.clientX,
                            endTy = touches.clientY,
                            distanceX = startTx - endTx,
                            distanceY = startTy - endTy;
                        if (distanceX < 0) { //右滑
                            if (Math.abs(distanceX) >= Math.abs(distanceY)) {
                                if (Math.abs(distanceX) > 20) {
                                    element.style.transition = "0.3s"
                                    element.style.marginLeft = 0 + "px"
                                }
                            }
                        } else { //左滑
                            if (Math.abs(distanceX) >= Math.abs(distanceY)) {
                                if (distanceX < 156 && distanceX > 20) {
                                    element.style.transition = "0s"
                                    element.style.marginLeft = -distanceX + "px"
                                    isTouchMove = true
                                }
                            }
                        }
                    }, { passive: false });
                    element.addEventListener('touchend', function (e) {
                        if (!isTouchMove) {
                            return;
                        }
                        var touches = e.changedTouches[0],
                            endTx = touches.clientX,
                            endTy = touches.clientY,
                            distanceX = startTx - endTx,
                            distanceY = startTy - endTy
                        // isSwipe = false
                        if (Math.abs(distanceX) >= Math.abs(distanceY)) {
                            if (distanceX < 0) {
                                return;
                            }
                            if (Math.abs(distanceX) < 60) {
                                // isSwipe = true
                                element.style.transition = "0.3s"
                                element.style.marginLeft = 0 + "px"
                            } else {
                                element.style.transition = "0.3s"
                                element.style.marginLeft = "-156px"
                            }
                        }
                    });
                }
            }
        }
    }
</script>